 /**
 * Description: 客服问题记录
 * @author:jacky
 * @since:1.0.0
 *
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2018-05-08   jacky       1.0.0     Initial
 */
package com.metro.demo.cust.controller;

import com.github.pagehelper.PageInfo;
import com.metro.core.annotation.BusinessDesc;
import com.metro.core.excel.JxlsView;
import com.metro.core.page.Page;
import com.metro.core.vo.JsonResult;
import com.metro.core.vo.QueryParams;
import com.metro.core.vo.ResultCode;
import com.metro.core.vo.inf.IResult;

import org.apache.ibatis.reflection.wrapper.BaseWrapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.metro.demo.cust.service.impl.BizCustAttachmentService;
import com.metro.demo.cust.service.inf.IBizCustAttachmentService;
import com.metro.demo.cust.service.inf.IBizCustomerManageService;
import com.metro.demo.material.beans.vo.BizMaterialManage;
import com.metro.demo.cust.beans.vo.BizCustAttachment;
import com.metro.demo.cust.beans.vo.BizCustomerManage;
import com.metro.demo.web.controller.BaseController;
import com.metro.demo.common.utils.DicUtil;
import com.metro.demo.biz.beans.vo.Biz4sInfoManage;
import com.metro.demo.common.beans.constant.DicTypeEnum;
import com.metro.demo.common.beans.constant.JxlsTemplateEnum;
import com.metro.demo.common.beans.constant.PropertiesEnum;
import com.metro.demo.common.beans.vo.WebUserInfo;
 /**
 * 客服问题记录<br>
 *
 * @author:jacky
 * @since:1.0.0
 * @version [1.0.0, 2018-05-08]
 */
@Controller
@RequestMapping("/bizCustomerManage")
public class BizCustomerManageController extends BaseController {
    //菜单编码
    private static final String menuCode = "BIZ_CUSTOMER_MANAGE";
    //模块描述
    private static final String MODULE_DESC = "客服问题记录";
    @Autowired
    private IBizCustomerManageService bizcustomermanageService;
    @Autowired
    private IBizCustAttachmentService bizCustAttachmentService;
    @Override
    protected String getViewDir() {
        return "cust/";
    }
    
    /**
     * 去查询客服问题记录
     * 
     * @param bizcustomermanage 客服问题记录页面表单对象
     * @param page 分页配置
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "查询客服问题记录列表")
    @RequiresPermissions(menuCode + ":view")
    @SuppressWarnings("all")
    @RequestMapping(value = "list", method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView list(BizCustomerManage bizcustomermanage) {
        ModelAndView mav = new ModelAndView();
        //获取用户的登录信息
    	Subject currentUser = SecurityUtils.getSubject();
        WebUserInfo userInfo  = (WebUserInfo)currentUser.getPrincipal();
        //获取登录用户名
        String username = userInfo.getUserName();
        try {
        	mav.addObject("solveProgresss", DicUtil.getLabelValueList(DicTypeEnum.SOLVE_PROGRESS));
        	mav.addObject("problemTypes", DicUtil.getLabelValueList(DicTypeEnum.PROBLEM_TYPE));
            mav.setViewName(getView("bizcustomermanage_list"));
            mav.addObject("username", username);
            mav.addObject("searchEntity", bizcustomermanage);
        } catch (Exception ex) {
            log.error("查询客服问题记录出错", ex);
            mav.addObject("ex", ex);
            mav.setViewName("/commons/error/error");
        }
        return mav;
    }

    /**
     * 查询客服问题记录
     *
     * @param bizcustomermanage 客服问题记录页面表单对象
     * @param page 分页配置
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "查询客服问题记录列表")
    @RequiresPermissions(menuCode + ":view")
    @SuppressWarnings("all")
    @RequestMapping(value = "dolist", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JsonResult dolist(BizCustomerManage bizcustomermanage, Page page, QueryParams<BizCustomerManage> queryParams) {
        JsonResult jr = new JsonResult();
        try {
            queryParams.setPaging(page);
            queryParams.setEntity(bizcustomermanage);
            PageInfo<BizCustomerManage> pageInfo = bizcustomermanageService.queryForPage(queryParams);
            jr.setData(pageInfo);
            jr.setResult(ResultCode.SUCCESS);
        } catch (Exception ex){
            log.error("查询客服问题记录出错",ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }

    /**
     * 去新增客服问题记录
     * 
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去新增客服问题记录")
    @RequiresPermissions(menuCode + ":add")
    @RequestMapping(value = "create")
    public ModelAndView createForm(Model model, HttpServletRequest request){
        ModelAndView mav = new ModelAndView();
        try {
            initCreateOrUpdateFrom(mav, "create");
        } catch (Exception ex) {
            log.error("去新增客服问题记录出错", ex);
            mav.addObject("ex", ex);
            mav.setViewName("/commons/error/error");
        }
        return mav;
    }
    
    /**
     * 初始化新增修改客服问题记录所需参数
     * @author jacky
     */
    private void initCreateOrUpdateFrom(ModelAndView mav, String action){
        mav.addObject("solveProgresss", DicUtil.getLabelValueList(DicTypeEnum.SOLVE_PROGRESS));
        mav.addObject("problemTypes", DicUtil.getLabelValueList(DicTypeEnum.PROBLEM_TYPE));
        mav.addObject("action", action);
        mav.setViewName(getView("bizcustomermanage_form"));
    }
    
    /**
     * 新增客服问题记录
     * 
     * @param entity 客服问题记录页面表单对象
     * @param request 请求对象
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "新增客服问题记录")
    @RequiresPermissions(menuCode + ":add")
    @RequestMapping(value = "save", method = { RequestMethod.POST})
    @ResponseBody
    public JsonResult saveBizCustomerManage(BizCustomerManage entity, HttpServletRequest request) {
        JsonResult jr = new JsonResult();
	    //获取用户的登录信息
	    Subject currentUser = SecurityUtils.getSubject();
	    WebUserInfo userInfo  = (WebUserInfo)currentUser.getPrincipal();
	    //获取登录用户名
	    String username = userInfo.getUserName();
	    entity.setRecorder(username);
	    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	    try {
			entity.setFeedbackDate(format.parse(entity.getFeedback()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
        try {
            IResult res = bizcustomermanageService.save(entity);
            jr.setResult(res);
            log.debug("新增客服问题记录成功【{}】", entity);
        } catch (Exception ex) {
            log.error("新增客服问题记录出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }

    /**
     * 删除客服问题记录
     * 
     * @param id 客服问题记录页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "删除客服问题记录")
    @RequiresPermissions(menuCode + ":delete")
    @RequestMapping(value = "delete/{id}", method = { RequestMethod.DELETE })
    @ResponseBody
    public JsonResult delete(@PathVariable String id, HttpServletRequest request){
        JsonResult jr = new JsonResult();
        try {
            log.debug("删除客服问题记录id={}",id);
            IResult codeMsg = bizcustomermanageService.deleteByIds(id);
            IResult msg = bizCustAttachmentService.deleteAttachment(id);
            jr.setResult(codeMsg);
        } catch (Exception ex) {
            log.error("删除客服问题记录出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }
    
    /**
     * 去修改客服问题记录
     * 
     * @param id 客服问题记录页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去修改客服问题记录")
    @RequiresPermissions(menuCode + ":edit")
    @RequestMapping(value = "edit/{id}", method = { RequestMethod.GET})
    public ModelAndView updateForm(@PathVariable Long id, HttpServletRequest request){
        ModelAndView mav = new ModelAndView();
        try {
            BizCustomerManage entity = bizcustomermanageService.getById(id);
            mav.addObject("entity", entity);
            initCreateOrUpdateFrom(mav,"edit");
        } catch (Exception ex) {
            log.error("去修改客服问题记录", ex);
            mav.setView(new RedirectView("list"));
        }
        return mav;
    }

    /**
     * 修改客服问题记录
     * 
     * @param entity 客服问题记录页面表单对象
     * @param request 请求对象
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "修改客服问题记录")
    @RequiresPermissions(menuCode + ":edit")
    @RequestMapping(value = "update", method = { RequestMethod.POST})
    @ResponseBody
    public JsonResult updateBizCustomerManage(BizCustomerManage entity, HttpServletRequest request) {
        JsonResult jr = new JsonResult();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	    try {
			entity.setFeedbackDate(format.parse(entity.getFeedback()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
        try {
            IResult res = bizcustomermanageService.update(entity);
            jr.setResult(res);
            log.debug("修改客服问题记录成功【{}】", entity);
        } catch (Exception ex) {
            log.error("修改客服问题记录出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }
    
    /**
     * 去查看客服问题记录
     * 
     * @param id 客服问题记录页面表单对象唯一标识
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去查看客服问题记录详情")
    @RequiresPermissions(menuCode + ":view")
    @RequestMapping(value = "info/{id}", method = { RequestMethod.GET })
    public ModelAndView info(@PathVariable Long id) {
        ModelAndView mav= new ModelAndView();
        try {
            mav.addObject("entity", bizcustomermanageService.getById(id));
            mav.setViewName(getView("bizcustomermanage_info"));
        } catch (Exception ex) {
            log.error("查看客服问题记录出错", ex);
        }
        return mav;
        
    }
    
    

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public ModelAndView export(BizCustomerManage entity) {
        List<BizCustomerManage> list = bizcustomermanageService.queryForList(entity);
        return new ModelAndView(new JxlsView(JxlsTemplateEnum.BIZCUSTOMERMANAGE, list));
    }
    
    /**
     * 去上传附件
     * 
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去上传附件")
    @RequestMapping(value = "upload/{id}")
    public ModelAndView show(@PathVariable Long id,Model model, HttpServletRequest request){
        ModelAndView mav = new ModelAndView();
        try {
        	 mav.addObject("id", id);
        	 mav.setViewName(getView("attachmentInput"));
        } catch (Exception ex) {
            log.error("去上传附件失败", ex);
            mav.addObject("ex", ex);
            mav.setViewName("/commons/error/error");
        }
        return mav;
    }

    
    /**
     * 文件上传
     * @param files
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST, produces = "application/json;charset=utf8")
    @ResponseBody
    public JsonResult uploadMultipleFile(@RequestParam("file") MultipartFile[] files,HttpServletRequest request) throws IOException {
    	JsonResult jr = new JsonResult();
    	ArrayList<Integer> arr = new ArrayList<>();
    	//获取用户的登录信息
    	Subject currentUser = SecurityUtils.getSubject();
        WebUserInfo userInfo  = (WebUserInfo)currentUser.getPrincipal();
        //获取登录用户名
        String username = userInfo.getUserName();
        //获取传入的id
        String custId=request.getParameter("id");
        //遍历接收到的文件
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i]; 
            if (!file.isEmpty()) {
                InputStream in = null;
                OutputStream out = null;
                //获取文件后缀名
                String fileName=file.getOriginalFilename();
                //获取后缀名
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                BizCustAttachment custEntity = new BizCustAttachment();
                if(suffix.equals("jpg") ||suffix.equals("png") ||suffix.equals("gif") ||suffix.equals("bmp") ||suffix.equals("jpeg")) {
                	custEntity.setType("1");
                }else{
                	custEntity.setType("2");
                }
                try {
                	
                	//获取系统文件上传根路径
                    String dir = PropertiesEnum.getPropertyValue(PropertiesEnum.FILE_UPLOAD_ROOT)+"/cust/"+custId+"/";
                    //如果路径不存在 则新建
                    File rootFile = new File(dir);
                    if(!rootFile.exists()){  
                    	rootFile.mkdirs();  
                    }
                    String path = dir+"/"+ fileName;
                    File serverFile = new File(path);
                    in = file.getInputStream();
                    out = new FileOutputStream(serverFile);
                    byte[] b = new byte[1024];
                    int len = 0;
                    while ((len = in.read(b)) > 0) {
                        out.write(b, 0, len);
                    }
                    out.close();
                    in.close();
                    //设置存入数据库的路径
                    String savePath = "/cust/"+custId+"/"+ fileName;
                    //经销商号码、名称、路径保存到数据库
                    custEntity.setCustId(Long.valueOf(custId));
                    custEntity.setPath(savePath);
                    //保存文件路径到数据库
                    IResult res = bizCustAttachmentService.save(custEntity);
                    //修改manage表attachment字段为有附件
                    BizCustomerManage entity = new BizCustomerManage();
                    entity.setAttachment("1");
                    entity.setId(Long.valueOf(custId));
                    bizcustomermanageService.updateAttachment(entity);
                    jr.setResult(res);

                } catch (Exception e) {
                    arr.add(i);
                } finally {
                    if (out != null) {
                        out.close();
                        out = null;
                    }

                    if (in != null) {
                        in.close();
                        in = null;
                    }
                }
            } else {
                arr.add(i);
            }
        }
        return jr;
    }
    
    /**
     * 附件查看
     * 
     * @param id 实施资料管理页面表单对象唯一标识
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-02]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去查看附件详情")
    @RequiresPermissions(menuCode + ":view")
    @RequestMapping(value = "show/{id}", method = { RequestMethod.GET })
    public ModelAndView info(@PathVariable String id) {
        ModelAndView mav= new ModelAndView(); 
        BizCustAttachment entity = new BizCustAttachment();
        try {
        	List<BizCustAttachment>  entitys = bizCustAttachmentService.queryById(Long.valueOf(id));
            mav.addObject("list",entitys);
            mav.setViewName(getView("bizattachment_show"));
        } catch (Exception ex) {
            log.error("查看附件出错", ex);
        }
        return mav;
        
    }
    
    /**
     * 视频查看
     * 
     * @param id 实施资料管理页面表单对象唯一标识
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-02]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去查看视频详情")
    @RequiresPermissions(menuCode + ":view")
    @RequestMapping(value = "showVedio", method = { RequestMethod.POST })
    public ModelAndView showVedio(String path) {
        ModelAndView mav= new ModelAndView(); 
        BizCustAttachment entity = new BizCustAttachment();
        try {
            mav.addObject("path",path);
            mav.setViewName(getView("bizattachment_show3"));
        } catch (Exception ex) {
            log.error("查看视频出错", ex);
        }
        return mav;
    }
    
    /**
     * 删除附件
     * 
     * @param id 实施资料管理页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-02]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "删除实施资料管理")
    @RequiresPermissions(menuCode + ":delete")
    @RequestMapping(value = "deleteAttachment", method = { RequestMethod.POST })
    @ResponseBody
    public JsonResult deleteAttachment(String id){
        JsonResult jr = new JsonResult();
        try {
            log.debug("删除实施资料管理id={}",id);
            IResult codeMsg = bizCustAttachmentService.deleteAttachment(id);
            //修改manage表attachment字段为无附件
            BizCustomerManage entity = new BizCustomerManage();
            entity.setAttachment("0");
            entity.setId(Long.valueOf(id));
            bizcustomermanageService.updateAttachment(entity);
            jr.setResult(codeMsg);
        } catch (Exception ex) {
            log.error("删除实施资料管理出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }
    
}
